//
// Created by martin on 5/1/22.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <libgen.h>
#include <assert.h>

/**
 * Run command:
 * $ ./a.out tee_out.txt
 */
int main(int argc, char* argv[])
{
    if (argc != 2) {
        printf("usage: %s <file>\n", basename(argv[0]));
        return 1;
    }
    int filefd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
    assert(filefd >= 0);

    int pipefd_stdout[2];
    int ret = pipe(pipefd_stdout);
    assert(ret != -1);

    int pipefd_file[2];
    ret = pipe(pipefd_file);
    assert(ret != -1);

    while (1) {
        /* 将标准输入内容输入管道pipe_stdout */
        ssize_t res = splice(STDIN_FILENO, NULL, pipefd_stdout[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
        if (res == 0) {
            printf("read EOF from stdin\n");
            break;
        }
        assert(res != -1);

        /* 将管道 pipefd_stdout 输出复制到 pipefd_file */
        res = tee(pipefd_stdout[0], pipefd_file[1], 32768, SPLICE_F_NONBLOCK);
        assert(res != -1);

        /* 将管道 pipefd_file 输出定向到文件描述符filefd 上 */
        res = splice(pipefd_file[0], NULL, filefd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
        assert(res != -1);
        /* 将管道 pipefd_file 输出定向到标准输出上. 之前已经对pipe_file[0]用过splice, 会消耗其数据,
        因此第二次调用不会有数据, 而且程序会阻塞到这里等待pipefd_file[0] 数据 */
//        res = splice(pipefd_file[0], NULL, STDOUT_FILENO, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
//        assert(res != -1);
        printf("one loop\n");
    }

    close(filefd);
    close(pipefd_stdout[0]);
    close(pipefd_stdout[1]);
    close(pipefd_file[0]);
    close(pipefd_file[1]);
    return 0;
}
